package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.dao.TaskDetailsDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.controller.TaskController;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j

public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    TaskController taskController;

    @Autowired
    TaskDao taskDao;

    @Autowired
    TaskDetailsDao taskDetailsDao;

    @Autowired
    MqttProducer mqttProducer;

    @Autowired
    TaskDetailsService taskDetailsService;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional
    public boolean createTask(TaskViewModel taskViewModel) {
        //1参数校验
        if (taskViewModel == null) {

            return false;
        }
        //1. 工单与机器状态校验
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());
        //2. 校验该机器是否有相同类型的未完成工单 以及
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        TaskEntity task = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, task);
        //工单编号taskId // 所属区域Id，regionId;// userName//创建人名称userName，
        // productTypeId;//工单类型id，// expect;//计划完成时间，// assignorId//指派人Id//工单编号
        String autoID = createAutoID();
        task.setTaskCode(autoID);
        //所属区域id
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vmInfo == null) {
            return false;
        }
        Long regionId = vmInfo.getRegionId();
        task.setRegionId(regionId);
        // userName//创建人名称userName，
        task.setUserName(taskController.getUserName());
        // productTypeId;//工单类型id，
        task.setProductTypeId(taskViewModel.getProductType());
        //计划完成时间
        task.setExpect(null);
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //地址
        task.setAddr(vmInfo.getNodeName());


        //判断工单类型
        if (VMSystem.TASK_TYPE_SUPPLY.equals(taskViewModel.getProductType())) {
            TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();


            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            for (TaskDetailsViewModel detail : details) {
                BeanUtils.copyProperties(detail, taskDetailsEntity);
                taskDetailsDao.insert(taskDetailsEntity);
                task.getTaskId();
            }
        }

        taskDao.insert(task);


        return true;

    }

    @Override
    public Boolean acceptTask(Long taskId, Integer userId) {
        QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TaskEntity::getTaskId, taskId);
        TaskEntity task = taskDao.selectOne(wrapper);
        if (!(VMSystem.TASK_STATUS_CREATE.equals(task.getTaskStatus()))) {
            throw new LogicException("订单状态异常");
        }

        if (!(userId.equals(task.getAssignorId()))) {
            throw new LogicException("订单异常，执行人不匹配");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        taskDao.updateById(task);
        return true;
    }

    @Override
    public Boolean cancelTask(Long taskId, Integer userId, CancelTaskViewModel vo) {


        QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TaskEntity::getTaskId, taskId);
        TaskEntity task = taskDao.selectOne(wrapper);
        if (!(VMSystem.ORDER_STATUS_VENDOUT_FAIL.equals(task.getTaskStatus()) || VMSystem.ORDER_STATUS_INVALID.equals(task.getTaskStatus()))) {
            throw new LogicException("订单状态异常");
        }

        if (!(userId.equals(task.getAssignorId()))) {
            throw new LogicException("订单异常，执行人不匹配");
        }

        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(vo.getDesc());
        taskDao.updateById(task);
        return true;
    }

    @Override
    public Boolean completeTask(Long taskId, Integer userId) {
        QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TaskEntity::getTaskId, taskId);
        TaskEntity task = taskDao.selectOne(wrapper);
        if (!(VMSystem.ORDER_STATUS_VENDOUT_FAIL.equals(task.getTaskStatus()) || VMSystem.ORDER_STATUS_INVALID.equals(task.getTaskStatus()))) {
            throw new LogicException("订单状态异常");
        }

        if (!(userId.equals(task.getAssignorId()))) {
            throw new LogicException("订单异常，执行人不匹配");
        }
        task.setTaskStatus(VMSystem.ORDER_STATUS_INVALID);
        taskDao.updateById(task);

        //如果是运维工单
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY
                || task.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            noticeVMServiceStatus(task);//运维工单封装与下发
        }
        //如果是补货工单!!!!---------------------------
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            noticeVMServiceSupply(task);
        }

        return true;
    }

    /**
     * 补货协议封装与下发
     *
     * @param task
     */
    private void noticeVMServiceSupply(TaskEntity task) {

        //1查询id明细表
        QueryWrapper<TaskDetailsEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TaskDetailsEntity::getTaskId, task.getTaskId());
        List<TaskDetailsEntity> list = taskDetailsService.list(wrapper);

        //封装类
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(task.getInnerCode());
        //补货数据
        ArrayList<SupplyChannel> supplyChannels = Lists.newArrayList();
        list.forEach(d ->
                {
                    SupplyChannel supplyChannel = new SupplyChannel();

                    supplyChannel.setChannelId(d.getChannelCode());//货到编号
                    supplyChannel.setCapacity(d.getExpectCapacity());//补货数量
                    supplyChannels.add(supplyChannel);
                }
        );
        supplyContract.setSupplyData(supplyChannels);
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, supplyContract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public String createAutoID() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String formatDate = sdf.format(date);
        String key = "task" + formatDate;
        //加上时间戳如果不需要
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //查询 key 是否存在，不存在返回 1 ，存在的话则⾃增加1
        Long autoID = redisTemplate.opsForValue().increment(key + formatDate, 1);
        //这⾥是 4 位id，如果位数不够可以⾃⾏修改，下⾯的意思是得到上⾯ key 的值，位数为 4 ，不够的话在左边补 0 ，⽐如  110 会变成  0110
        String value = StringUtils.leftPad(String.valueOf(autoID), 3, "0");
        //然后把时间戳和优化后的 ID 拼接
        String code = MessageFormat.format("{0}{1}", datetime, value);
        //设置三天过期
        redisTemplate.expire(key + datetime, 1, TimeUnit.DAYS);
        return code;
    }

    /**
     * 创建工单校验
     *
     * @param innerCode   设备编号
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode, int productType) throws LogicException {
        VmVO vmInfo = vmService.getVMInfo(innerCode);//根据设备编号查询设备
        if (vmInfo == null) throw new LogicException("设备校验失败");
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

    /**
     * 运维工单封装与下发
     *
     * @param task
     */
    private void noticeVMServiceStatus(TaskEntity task) {
        //向消息队列发送消息，通知售货机更改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(task.getInnerCode());//售货机编号
        taskCompleteContract.setTaskType(task.getProductTypeId());//工单类型
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }
}
